package com.aistar.util;

import com.aistar.pojoVO.JudgeResult;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.Serializable;


public class JudgeUtil {
    private static final String URL = "http://122.51.240.124:9999/judge";

    private static String bean2String(Serializable bean) {
        return JSON.toJSONString(bean);
    }

    private static JSONObject run(String jsonString) {
        HttpClient client = HttpClients.createDefault();
        HttpPost post = new HttpPost(URL);
        try {
            StringEntity s = new StringEntity(jsonString);
            s.setContentEncoding("UTF-8");
            s.setContentType("application/json");
            post.setEntity(s);
            post.addHeader("content-type", "application/json");
            HttpResponse res = client.execute(post);
            String result = EntityUtils.toString(res.getEntity());
            return JSONObject.parseObject(result);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private static JudgeResult json2Bean(JSONObject jsonObject) {
        return JSON.toJavaObject(jsonObject, JudgeResult.class);
    }

    public static JudgeResult doPost(Serializable bean) {
        String input = bean2String(bean);
        JSONObject output = run(input);
        return json2Bean(output);
    }

//    public static void main(String[] args) {
//        String[] inputList = {"99 1", "99 1", "99 1", "99 1"};
//        String[] outputList = {"98", "991", "99 1", "100"};
//        JudgeTask judgeTask = new JudgeTask(inputList, outputList,
//                1000L, 65535L, 1,
//                "#include<stdio.h>\nint main()\n{\n\tint a,b,sum;\n\tscanf(\"%d %d\",&a,&b);\n\tsum=a+b;\n\tprintf(\"%d\",sum);\n\treturn 0;\n}"
//        );
//        JudgeResult output = JudgeUtil.doPost(judgeTask);
//        System.out.println(output);
//    }
}
